<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js,js 机制," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="前言最近正在看《你不知道的JavaScript》，里面关于this绑定机制的部分讲的特别好，很清晰，这部分对我们js的使用也是相当关键的，并且这也是一个面试的高频考点，所以整理一篇文章分享一下这部分的内容，相信看本文的解析，你一定会有所收获的，如果喜欢的话可以点波赞/关注，支持一下。">
<meta name="keywords" content="js,js 机制">
<meta property="og:type" content="article">
<meta property="og:title" content="你不知道的js中关于this绑定机制的解析[看完还不懂算我输]">
<meta property="og:url" content="http://yoursite.com/2018/06/30/你不知道的js中关于this绑定机制的解析-看完还不懂算我输/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="前言最近正在看《你不知道的JavaScript》，里面关于this绑定机制的部分讲的特别好，很清晰，这部分对我们js的使用也是相当关键的，并且这也是一个面试的高频考点，所以整理一篇文章分享一下这部分的内容，相信看本文的解析，你一定会有所收获的，如果喜欢的话可以点波赞/关注，支持一下。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fstcwvzkjzj30sg0g0qqn.jpg?raw=true">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true">
<meta property="og:updated_time" content="2019-07-20T06:55:39.068Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="你不知道的js中关于this绑定机制的解析[看完还不懂算我输]">
<meta name="twitter:description" content="前言最近正在看《你不知道的JavaScript》，里面关于this绑定机制的部分讲的特别好，很清晰，这部分对我们js的使用也是相当关键的，并且这也是一个面试的高频考点，所以整理一篇文章分享一下这部分的内容，相信看本文的解析，你一定会有所收获的，如果喜欢的话可以点波赞/关注，支持一下。">
<meta name="twitter:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fstcwvzkjzj30sg0g0qqn.jpg?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/06/30/你不知道的js中关于this绑定机制的解析-看完还不懂算我输/"/>





  <title>你不知道的js中关于this绑定机制的解析[看完还不懂算我输] | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/06/30/你不知道的js中关于this绑定机制的解析-看完还不懂算我输/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">你不知道的js中关于this绑定机制的解析[看完还不懂算我输]</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-30T18:29:19+08:00">
                2018-06-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/06/30/你不知道的js中关于this绑定机制的解析-看完还不懂算我输/" class="leancloud_visitors" data-flag-title="你不知道的js中关于this绑定机制的解析[看完还不懂算我输]">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,556 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1fstcwvzkjzj30sg0g0qqn.jpg?raw=true" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>最近正在看《你不知道的JavaScript》，里面关于this绑定机制的部分讲的特别好，很清晰，这部分对我们js的使用也是相当关键的，并且这也是一个面试的高频考点，所以整理一篇文章分享一下这部分的内容，相信看本文的解析，你一定会有所收获的，如果喜欢的话可以点波赞/关注，支持一下。</p>
<a id="more"></a>
<blockquote>
<p>个人博客了解一下：<a href="http://obkoro1.com/" target="_blank" rel="noopener">obkoro1.com</a></p>
</blockquote>
<hr>
<h3 id="为什么要用this："><a href="#为什么要用this：" class="headerlink" title="为什么要用this："></a>为什么要用this：</h3><pre><code>function identify() {
  console.log(&quot;Hello,I&apos;m &quot; + this.name);
}
let me = {
  name: &quot;Kyle&quot;
};
let you = {
  name: &quot;Reader&quot;
};
identify.call(me); // Hello,I&apos;m Kyle
identify.call(you); // Hello,I&apos;m Reader
</code></pre><p>这个简单的栗子，可以在不同的对象中复用函数<code>identify</code>，不用针对每个对象编写一个新函数。</p>
<p><strong>this解决的问题:</strong></p>
<p>this提供了一种更优雅的方法来隐式’传递’一个对象的引用，因此可以<strong>将API设计得更加简洁并且易于复用</strong>。</p>
<h2 id="this的四种绑定规则："><a href="#this的四种绑定规则：" class="headerlink" title="this的四种绑定规则："></a>this的四种绑定规则：</h2><h3 id="默认绑定："><a href="#默认绑定：" class="headerlink" title="默认绑定："></a>默认绑定：</h3><p><strong>规则</strong>：在非严格模式下，默认绑定的<code>this</code>指向全局对象，严格模式下<code>this</code>指向undefined</p>
<pre><code>function foo() {
  console.log(this.a); // this指向全局对象
}
var a = 2;
foo(); // 2
function foo2() {
  &quot;use strict&quot;; // 严格模式this绑定到undefined
  console.log(this.a); 
}
foo2(); // TypeError:a undefined
</code></pre><p>默认绑定规则如上述栗子，书中还提到了一个微妙的细节：</p>
<pre><code>function foo() {
  console.log(this.a); // foo函数不是严格模式 默认绑定全局对象
}
var a = 2;
function foo2(){
  &quot;use strict&quot;;
  foo(); // 严格模式下调用其他函数，不影响默认绑定
}
foo2(); // 2
</code></pre><p>所以：对于默认绑定来说，<strong>决定this绑定对象的是函数体是否处于严格模式</strong>，严格指向undefined，非严格指向全局对象。</p>
<p>通常不会在代码中混用严格模式和非严格模式，所以这种情况很罕见，知道一下就可以了，避免某些变态的面试题挖坑。</p>
<h3 id="隐式绑定："><a href="#隐式绑定：" class="headerlink" title="隐式绑定："></a>隐式绑定：</h3><p><strong>规则</strong>：函数在调用位置，是否有上下文对象，如果有，那么this就会隐式绑定到这个对象上。</p>
<pre><code>function foo() {
  console.log(this.a);
}
var a = &quot;Oops, global&quot;;
let obj2 = {
  a: 2,
  foo: foo
};
let obj1 = {
  a: 22,
  obj2: obj2
};
obj2.foo(); // 2 this指向调用函数的对象
obj1.obj2.foo(); // 2 this指向最后一层调用函数的对象

// 隐式绑定丢失
let bar = obj2.foo; // bar只是一个函数别名 是obj2.foo的一个引用
bar(); // &quot;Oops, global&quot; - 指向全局
</code></pre><p><strong>隐式绑定丢失：</strong></p>
<p>隐式绑定丢失的问题：<strong>实际上就是函数调用时，并没有上下文对象，只是对函数的引用</strong>，所以会导致隐式绑定丢失。</p>
<p>同样的问题，还发生在传入回调函数中，这种情况更加常见，并且隐蔽，类似：</p>
<pre><code>test(obj2.foo); // 传入函数的引用，调用时也是没有上下文对象。
</code></pre><h3 id="显式绑定"><a href="#显式绑定" class="headerlink" title="显式绑定:"></a>显式绑定:</h3><p>就像我们上面看到的，如果单纯使用隐式绑定肯定没有办法得到期望的绑定，幸好我们还可以<strong>在某个对象上强制调用函数，从而将<code>this</code>绑定在这个函数上</strong>。</p>
<p><strong>规则</strong>：我们可以通过<code>apply</code>、<code>call</code>、<code>bind</code>将函数中的<code>this</code>绑定到指定对象上。</p>
<pre><code>function foo() {
    console.log(this.a);
}
let obj = {
    a: 2
};
foo.call(obj); // 2
</code></pre><p><strong>传入的不是对象：</strong></p>
<p>如果你传入了一个原始值(字符串,布尔类型，数字类型)，来当做this的绑定对象，这个原始值转换成它的对象形式。</p>
<p>如果你把<code>null</code>或者<code>undefined</code>作为this的绑定对象传入<code>call</code>/<code>apply</code>/<code>bind</code>，这些值会在调用时被忽略，实际应用的是默认绑定规则。</p>
<h3 id="new绑定："><a href="#new绑定：" class="headerlink" title="new绑定："></a>new绑定：</h3><blockquote>
<p>书中提到：在js中，实际上并不存在所谓的’构造函数’，只有对于函数的’构造调用’。</p>
</blockquote>
<p><strong>new的时候会做哪些事情：</strong></p>
<ol>
<li><strong>创建一个全新的对象</strong>。</li>
<li>这个新对象会被执行 [[Prototype]] 连接。</li>
<li><strong>这个新对象会绑定到函数调用的this</strong>。</li>
<li>如果函数没有返回其他对象，那么new表达式中的函数调用会自动返回这个新对象。</li>
</ol>
<p><strong>规则</strong>：使用构造调用的时候，this会自动绑定在new期间创建的对象上。</p>
<pre><code>function foo(a) {
  this.a = a; // this绑定到bar上
}
let bar = new foo(2);
console.log(bar.a); // 2
</code></pre><h3 id="this四种绑定规则的优先级"><a href="#this四种绑定规则的优先级" class="headerlink" title="this四种绑定规则的优先级"></a>this四种绑定规则的优先级</h3><p>如果在某个调用位置应用了多条规则，如何确定哪条规则生效？</p>
<pre><code>obj.foo.call(obj2); // this指向obj2 显式绑定比隐式绑定优先级高。
new obj.foo(); // thsi指向new新创建的对象 new绑定比隐式绑定优先级高。
</code></pre><p>显式绑定和隐式绑定无法直接比较(会报错),默认绑定是不应用其他规则之后的兜底绑定所以优先级最低，最后的结果是：</p>
<p><strong>显式绑定 &gt; 隐式绑定 &gt; 默认绑定</strong></p>
<p><strong>new绑定 &gt; 隐式绑定 &gt; 默认绑定</strong></p>
<h3 id="箭头函数的this指向不会使用上述的四条规则："><a href="#箭头函数的this指向不会使用上述的四条规则：" class="headerlink" title="箭头函数的this指向不会使用上述的四条规则："></a>箭头函数的this指向不会使用上述的四条规则：</h3><pre><code>function foo() {
  return () =&gt; {
    console.log(this.a);
  };
}
let obj1 = {
  a: 2
};
let obj2 = {
  a: 22
};
let bar = foo.call(obj1); // foo this指向obj1
bar.call(obj2); // 输出2 这里执行箭头函数 并试图绑定this指向到obj2
</code></pre><p>从上述栗子可以得出，箭头函数的this规则：</p>
<ol>
<li><strong>箭头函数中的<code>this</code>继承于它外面第一个不是箭头函数的函数的<code>this</code>指向</strong>。</li>
<li><strong>箭头函数的 this 一旦绑定了上下文，就不会被任何代码改变</strong>。</li>
</ol>
<hr>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>认真看完的话，相信你已经get到this的用法了，最后推荐一下《你不知道的JavaScript》，这本书真的很好，写的也很有趣，没看过的小伙伴抓紧入手了。</p>
<p>PS：目前离职中，大佬们有坑位可以介绍一下呀，base：上海长宁。</p>
<h3 id="希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。"><a href="#希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。" class="headerlink" title="希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。"></a>希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。</h3><p><strong><a href="http://obkoro1.com/" target="_blank" rel="noopener">个人blog</a></strong> and <strong><a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" rel="noopener">掘金个人主页</a></strong>，如需转载，请放上原文链接并署名。码字不易，<strong>感谢</strong>支持！</p>
<p>如果喜欢本文的话，欢迎关注我的订阅号，漫漫技术路，期待未来共同学习成长。</p>
<p><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" alt=""></p>
<p> 以上2018.6.30</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          
            <a href="/tags/js-机制/" rel="tag"><i class="fa fa-tag"></i> js 机制</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/24/160行代码仿Vue实现极简双向绑定-详细注释/" rel="next" title="160行代码仿Vue实现极简双向绑定[详细注释]">
                <i class="fa fa-chevron-left"></i> 160行代码仿Vue实现极简双向绑定[详细注释]
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/07/08/JS高程中的垃圾回收机制与常见内存泄露的解决方法/" rel="prev" title="JS高程中的垃圾回收机制与常见内存泄露的解决方法">
                JS高程中的垃圾回收机制与常见内存泄露的解决方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么要用this："><span class="nav-number">1.1.</span> <span class="nav-text">为什么要用this：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#this的四种绑定规则："><span class="nav-number">2.</span> <span class="nav-text">this的四种绑定规则：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#默认绑定："><span class="nav-number">2.1.</span> <span class="nav-text">默认绑定：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#隐式绑定："><span class="nav-number">2.2.</span> <span class="nav-text">隐式绑定：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#显式绑定"><span class="nav-number">2.3.</span> <span class="nav-text">显式绑定:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#new绑定："><span class="nav-number">2.4.</span> <span class="nav-text">new绑定：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#this四种绑定规则的优先级"><span class="nav-number">2.5.</span> <span class="nav-text">this四种绑定规则的优先级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#箭头函数的this指向不会使用上述的四条规则："><span class="nav-number">2.6.</span> <span class="nav-text">箭头函数的this指向不会使用上述的四条规则：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">3.</span> <span class="nav-text">结语</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。"><span class="nav-number">3.1.</span> <span class="nav-text">希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

